package com.atos.optical.config;

import com.atos.optical.Enums.StaticEnums;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author wanghra
 * @version 1.0
 * @description
 * @date 2025/8/12
 */
@Slf4j
@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {
    @Value("${mybatis-plus.global-config.db-config.logic-not-delete-value}")
    public String logicNotDeleteValue;

    @Override
    public void insertFill(MetaObject metaObject) {
        // 新增日期
        if (metaObject.hasSetter(StaticEnums.CREATE_TIME_KEY) && null == getFieldValByName(StaticEnums.CREATE_TIME_KEY, metaObject)) {
            log.debug("class:[MybatisMetaObjectHandler],method:[insertFill],message:[自动填充字段[createTime]]");
            this.setFieldValByName(StaticEnums.CREATE_TIME_KEY, LocalDateTime.now(), metaObject);
        }
        // 伪删除初始值
        if (metaObject.hasSetter(StaticEnums.IS_DELETED_KEY) && null == getFieldValByName(StaticEnums.IS_DELETED_KEY, metaObject)) {
            log.debug("class:[MybatisMetaObjectHandler],method:[insertFill],message:[自动填充字段[isDeleted]]");
            this.setFieldValByName(StaticEnums.IS_DELETED_KEY, logicNotDeleteValue, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 修改日期
        if (metaObject.hasSetter(StaticEnums.MODIFY_TIME_KEY)) {
            log.debug("class:[MybatisMetaObjectHandler],method:[updateFill],message:[自动填充字段[modifyTime]]");
            this.setFieldValByName(StaticEnums.MODIFY_TIME_KEY, LocalDateTime.now(), metaObject);
        }
    }
}
